{% extends "base.html" %}

{% block title %}单次爬取 - 安居客租房数据爬取系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-8 mx-auto">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><i class="fas fa-spider me-2"></i>爬虫任务配置</h4>
            </div>
            <div class="card-body">
                <form id="spiderForm">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="city" class="form-label">城市</label>
                            <select class="form-select" id="city" name="city" required>
                                <option value="">请选择城市</option>
                                {% for city in config.SUPPORTED_CITIES %}
                                    <option value="{{ city }}">{{ city }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="district" class="form-label">区域</label>
                            <select class="form-select" id="district" name="district">
                                <option value="">全部区域</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="min_price" class="form-label">最低价格 (元/月)</label>
                            <input type="number" class="form-control" id="min_price" name="min_price" placeholder="0">
                        </div>
                        <div class="col-md-6">
                            <label for="max_price" class="form-label">最高价格 (元/月)</label>
                            <input type="number" class="form-control" id="max_price" name="max_price" placeholder="不限">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="room_type" class="form-label">房间类型</label>
                            <select class="form-select" id="room_type" name="room_type">
                                {% for room_name, room_value in config.ROOM_TYPES.items() %}
                                    <option value="{{ room_value }}">{{ room_name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="source_type" class="form-label">房源来源</label>
                            <select class="form-select" id="source_type" name="source_type">
                                {% for source_name, source_value in config.SOURCE_TYPES.items() %}
                                    <option value="{{ source_value }}">{{ source_name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="max_pages" class="form-label">最大爬取页数</label>
                            <input type="number" class="form-control" id="max_pages" name="max_pages" value="5" min="1" max="20">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">其他选项</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="get_details" name="get_details">
                                <label class="form-check-label" for="get_details">
                                    获取详细房源信息
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg" id="startBtn">
                            <i class="fas fa-play me-2"></i>开始爬取
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card mt-4 d-none" id="progressCard">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-tasks me-2"></i>任务进度</h5>
            </div>
            <div class="card-body">
                <div id="taskInfo">
                    <div class="d-flex justify-content-between mb-2">
                        <span id="taskStatus">状态: 准备中...</span>
                        <span id="taskProgress">0%</span>
                    </div>
                    <div class="progress mb-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated"
                             id="progressBar" style="width: 0%"></div>
                    </div>
                    <p id="taskMessage" class="text-muted">正在初始化任务...</p>
                    <div id="taskResults" class="d-none">
                        <hr>
                        <h6>爬取结果</h6>
                        <p>共获取 <span id="resultsCount">0</span> 条房源信息</p>
                        <button class="btn btn-success btn-sm" id="downloadBtn">
                            <i class="fas fa-download me-1"></i>下载Excel文件
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" id="viewResultsBtn">
                            <i class="fas fa-eye me-1"></i>查看详情
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="resultsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">爬取结果详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="resultsContent">
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 城市选择变化时加载区域
    $('#city').change(function() {
        const city = $(this).val();
        if (city) {
            $('#district').html('<option value="">加载中...</option>');
            $.get('/get_city_districts/' + city, function(data) {
                let options = '<option value="">全部区域</option>';
                data.districts.forEach(function(district) {
                    options += '<option value="' + district + '">' + district + '</option>';
                });
                $('#district').html(options);
            });
        } else {
            $('#district').html('<option value="">全部区域</option>');
        }
    });

    // 表单提交
    $('#spiderForm').submit(function(e) {
        e.preventDefault();

        const formData = {
            city: $('#city').val(),
            district: $('#district').val(),
            min_price: $('#min_price').val(),
            max_price: $('#max_price').val(),
            room_type: $('#room_type').val(),
            source_type: $('#source_type').val(),
            max_pages: $('#max_pages').val(),
            get_details: $('#get_details').is(':checked')
        };

        // 验证必填字段
        if (!formData.city) {
            alert('请选择城市');
            return;
        }

        $('#startBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>任务启动中...');
        $('#progressCard').removeClass('d-none');

        // 启动任务
        $.ajax({
            url: '/start_task',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    const taskId = response.task_id;
                    checkTaskStatus(taskId);
                } else {
                    alert('启动任务失败: ' + response.message);
                    $('#startBtn').prop('disabled', false).html('<i class="fas fa-play me-2"></i>开始爬取');
                }
            },
            error: function() {
                alert('网络错误，请重试');
                $('#startBtn').prop('disabled', false).html('<i class="fas fa-play me-2"></i>开始爬取');
            }
        });
    });

    // 检查任务状态
    function checkTaskStatus(taskId) {
        $.get('/task_status/' + taskId, function(data) {
            if (data.error) {
                $('#taskStatus').text('错误: ' + data.error);
                return;
            }

            $('#taskStatus').text('状态: ' + getStatusText(data.status));
            $('#taskProgress').text(data.progress + '%');
            $('#progressBar').css('width', data.progress + '%');
            $('#taskMessage').text(data.message);

            if (data.status === 'completed') {
                $('#taskResults').removeClass('d-none');
                $('#resultsCount').text(data.results_count);

                // 设置下载按钮
                $('#downloadBtn').off('click').on('click', function() {
                    window.location.href = '/download/' + taskId;
                });

                // 设置查看详情按钮
                $('#viewResultsBtn').off('click').on('click', function() {
                    showTaskResults(taskId);
                });

                $('#startBtn').prop('disabled', false).html('<i class="fas fa-play me-2"></i>开始爬取');
            } else if (data.status === 'error') {
                $('#startBtn').prop('disabled', false).html('<i class="fas fa-play me-2"></i>开始爬取');
                setTimeout(() => checkTaskStatus(taskId), 2000);
            } else {
                // 继续检查状态
                setTimeout(() => checkTaskStatus(taskId), 2000);
            }
        });
    }

    // 显示任务结果
    function showTaskResults(taskId) {
        $('#resultsContent').html('<p>加载中...</p>');
        $('#resultsModal').modal('show');

        $.get('/task_results/' + taskId, function(data) {
            if (data.error) {
                $('#resultsContent').html('<p class="text-danger">' + data.error + '</p>');
                return;
            }

            let html = '<p>共获取 ' + data.total_count + ' 条房源信息，以下是前100条预览：</p>';
            html += '<div class="table-responsive"><table class="table table-striped table-sm"><thead><tr>';

            // 表头
            if (data.preview_results.length > 0) {
                const firstRow = data.preview_results[0];
                for (const key in firstRow) {
                    html += '<th>' + key + '</th>';
                }
                html += '</tr></thead><tbody>';

                // 数据行
                data.preview_results.forEach(function(house) {
                    html += '<tr>';
                    for (const key in firstRow) {
                        let value = house[key] || '';
                        if (typeof value === 'string' && value.length > 50) {
                            value = value.substring(0, 50) + '...';
                        }
                        html += '<td>' + value + '</td>';
                    }
                    html += '</tr>';
                });
                html += '</tbody></table></div>';
            } else {
                html += '<p>没有数据</p>';
            }

            $('#resultsContent').html(html);
        });
    }

    // 状态文本转换
    function getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'running': '执行中',
            'completed': '已完成',
            'error': '错误'
        };
        return statusMap[status] || status;
    }
});
</script>
{% endblock %}